using UnityEngine;


namespace ZTools.ZSingletons
{
    /// 持久化单例模式
    /// 项目从头到尾都保持这一单例对象
    public class ZPersistentSingleton<T> : MonoBehaviour where T : Component
    {
        [Header("持久化单例模式")] [Tooltip("如果为真, 该单例会自动从父组件分离")]
        public bool AutomaticallyUnparentOnAwake = true;

        protected static T _instance;
        private static bool HasInstance => _instance != null;

        public static T TryGetInstance() => HasInstance ? _instance : null;
        public static T Current => _instance;
        protected bool _enabled;


        public static T Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = FindFirstObjectByType<T>();
                    if (_instance == null)
                    {
                        var obj = new GameObject
                        {
                            name = typeof(T).Name + "_AutoCreated"
                        };
                        _instance = obj.AddComponent<T>();
                    }
                }

                return _instance;
            }
        }


        protected virtual void Awake()
        {
            if (!Application.isPlaying)
            {
                return;
            }

            if (AutomaticallyUnparentOnAwake)
            {
                this.transform.SetParent(null);
            }

            if (_instance == null)
            {
                // 将当前对象作为第一个单例
                _instance = this as T;
                DontDestroyOnLoad(transform.gameObject);
                _enabled = true;
            }
            else
            {
                // 如果单例已存在,且当前对象与单例中的对象不一致, 删除当前对象
                if (this != _instance)
                {
                    Destroy(this.gameObject);
                }
            }

            _instance = this as T;
        }
    }
}